#include "EchoServer.h"

EchoServer::EchoServer(std::string &ip, uint16_t &port)
    :tcpserver_(ip, port)
{
    tcpserver_.setnewConnectioncb(std::bind(&EchoServer::HandlenewConnection, this, std::placeholders::_1));
    tcpserver_.setcloseConnectioncb(std::bind(&EchoServer::Handlecloseconnection, this, std::placeholders::_1));
    tcpserver_.seterrorConnectioncb(std::bind(&EchoServer::Handleerrorconnection, this, std::placeholders::_1));
    tcpserver_.setonMessagecb(std::bind(&EchoServer::HandleMessage, this, std::placeholders::_1, std::placeholders::_2));
    tcpserver_.setsendCompletecb(std::bind(&EchoServer::Handlesendcomplete, this, std::placeholders::_1));
    tcpserver_.setepollTimeoutcb(std::bind(&EchoServer::Handleepolltimeout, this, std::placeholders::_1));   

}
EchoServer::~EchoServer()
{
}

void EchoServer::Handlestart()
{
    tcpserver_.start();
}
void EchoServer::HandlenewConnection(Connection *conn)
{
    printf("new connection\n");
    // 根据业务的需求可以增加其他的带啊吗
}

void EchoServer::Handlecloseconnection(Connection *conn)
{
    printf("connection  closed\n");
    // 根据业务的需求可以增加其他的带啊吗
}
void EchoServer::Handleerrorconnection(Connection *conn)
{
    printf("connection error\n");
}
void EchoServer::HandleMessage(Connection *conn, std::string& message)
{
    // 处理客户端的请求报文
    message = "reply" + message; // 得到处理后的结果


    // 报文长度 和 报文内容
    // int len = message.size();
    // std::string tempbuf((char *)&len, 4);
    // tempbuf.append(message);
    // conn->outputbuffer_ = conn->inputbuffer_;
    // inputbuffer_.clear();
    // send(conn->fd(), tempbuf.data(), tempbuf.size(), 0);
    conn->send(message.data(), message.size()); //把数据发送出去
}

void EchoServer::Handlesendcomplete(Connection *conn)
{
    printf("send complete\n");
}

void EchoServer::Handleepolltimeout(EventLoop *loop)
{
    printf("EchoServer timeout\n");
}